package com.hfstu.framework.core.orm.hibernate;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.internal.CriteriaImpl;
import org.hibernate.transform.ResultTransformer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hfstu.framework.core.orm.Page;
import com.hfstu.framework.core.orm.PageRequest;
import com.hfstu.framework.core.orm.PageRequest.Sort;
import com.hfstu.framework.core.orm.PropertyFilter;
import com.hfstu.framework.core.orm.PropertyFilter.MatchType;
import com.hfstu.framework.core.utils.AssertUtils;
import com.hfstu.framework.core.utils.reflection.ReflectionUtils;
import com.hfstu.framework.model.BaseModel;
import com.hfstu.framework.util.QueryUtil;
import com.hfstu.framework.util.StringUtil;

@SuppressWarnings("all")
public class PageDAOSpringTemplate<T extends BaseModel, PK extends Serializable>
		extends BaseGenericDAOImpl<T, PK> {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	public String getHql(String hql, Map<String, Object> filterPropertyMap,
			Map<String, String> sortValueMap) {
		StringBuilder sql = new StringBuilder();
		sql.append(hql);

		StringBuilder whereSql = new StringBuilder();
		if (!(hql.indexOf("where") != -1 || hql.indexOf("WHERE") != -1)) {
			whereSql.append(" where 1 = 1");
		}
		StringBuilder orderbySql = new StringBuilder();

		if (!(null == filterPropertyMap || filterPropertyMap.isEmpty())) {

			Object value = null;
			Set<String> keys = filterPropertyMap.keySet();
			for (String key : keys) {
				value = filterPropertyMap.get(key);

				if (value == null) {
					continue;
				}
				if (value instanceof Integer || value instanceof Long
						|| value instanceof Double || value instanceof Float
						|| value instanceof Boolean) {
					if (value != null) {
						whereSql.append(" and ").append(key).append(" = ")
								.append(value);
					}

				} else if (value instanceof String) {
					if (!value.equals("")) {
						whereSql.append(" and ").append(key).append(" like '%")
								.append(StringUtil.clean((String) value))
								.append("%'");
					}
				} else if (value instanceof Object[]) {
					Object[] dateStrings = (Object[]) value;
					if (dateStrings.length != 2) {
						throw new RuntimeException("请按照格式输入开始时间和结束时间");
					}
					if (!dateStrings[0].equals("")) {
						whereSql.append(" and ").append(key).append(" >= ")
								.append(dateStrings[0]);
					}
					if (!dateStrings[1].equals("")) {
						whereSql.append(" and ").append(key).append(" <= ")
								.append(dateStrings[1]);
					}
				} else {
					// 除了这几种类型外，报错
					throw new RuntimeException("还有其他类型，请重新配置");
				}
				value = null;
			}
			sql.append(whereSql);
		}
		if (!(null == sortValueMap || sortValueMap.isEmpty())) {

			String value;
			Set<String> keys = sortValueMap.keySet();
			for (String key : keys) {
				value = sortValueMap.get(key);
				if (!StringUtil.isNullOrEmpty(key)
						&& !StringUtil.isNullOrEmpty(value)) {
					if (orderbySql.length() == 0) {
						orderbySql.append(" order by ");
					}
					orderbySql.append(StringUtil.clean(key)).append(" ")
							.append(StringUtil.clean(value)).append(",");
				}

			}
			if (orderbySql.length() > 0) {
				if (orderbySql.charAt(orderbySql.length() - 1) == ',') {
					orderbySql.deleteCharAt(orderbySql.length() - 1);
				}
			}
			sql.append(orderbySql);
		}

		return sql.toString();
	}

	public Criterion[] getCriterions(Map<String, Object> filterPropertyMap) {
		List<Criterion> criterionList = new ArrayList<Criterion>();

		if (!(null == filterPropertyMap || filterPropertyMap.isEmpty())) {

			Object value = null;
			Set<String> keys = filterPropertyMap.keySet();
			for (String key : keys) {
				value = filterPropertyMap.get(key);

				if (value == null) {
					continue;
				}
				if (value instanceof Integer || value instanceof Long
						|| value instanceof Double || value instanceof Float
						|| value instanceof Boolean) {
					if (value != null) {
						criterionList.add(Restrictions.eq(key, value));
					}

				} else if (value instanceof String) {
					if (!StringUtil.isNullOrEmpty((String) value)) {
						criterionList.add(Restrictions.like(key, value));
					}
				} else if (value instanceof Object[]) {
					Object[] dateStrings = (Object[]) value;
					if (dateStrings.length != 2) {
						throw new RuntimeException("请按照格式输入开始时间和结束时间");
					}
					if (!dateStrings[0].equals("")) {
						criterionList.add(Restrictions.ge(key, dateStrings[0]));
					}
					if (!dateStrings[1].equals("")) {
						criterionList.add(Restrictions.le(key, dateStrings[1]));
					}
				} else {
					// 除了这几种类型外，报错
					throw new RuntimeException("还有其他类型，请重新配置");
				}
				value = null;
			}
		}

		return criterionList.toArray(new Criterion[criterionList.size()]);
	}

	public void addOrderCriteria(Criteria criteria,
			Map<String, String> sortValueMap) {
		if (!(null == sortValueMap || sortValueMap.isEmpty())) {

			String value;
			Set<String> keys = sortValueMap.keySet();
			for (String key : keys) {
				value = sortValueMap.get(key);
				if (!StringUtil.isNullOrEmpty(key)
						&& !StringUtil.isNullOrEmpty(value)) {
					if (value.equalsIgnoreCase("desc")) {
						criteria.addOrder(Order.desc(key));
					}
					if (value.equalsIgnoreCase("asc")) {
						criteria.addOrder(Order.asc(key));
					}

				}

			}
		}

	}

	public void addOrderCriteria(DetachedCriteria criteria,
			Map<String, String> sortValueMap) {
		if (!(null == sortValueMap || sortValueMap.isEmpty())) {

			String value;
			Set<String> keys = sortValueMap.keySet();
			for (String key : keys) {
				value = sortValueMap.get(key);
				if (!StringUtil.isNullOrEmpty(key)
						&& !StringUtil.isNullOrEmpty(value)) {
					if (value.equalsIgnoreCase("desc")) {
						criteria.addOrder(Order.desc(key));
					}
					if (value.equalsIgnoreCase("asc")) {
						criteria.addOrder(Order.asc(key));
					}

				}

			}
		}

	}

	public Page<T> findPageByCondition(final PageRequest pageRequest,
			String hql, Map<String, Object> filterPropertyMap,
			Map<String, String> sortValueMap) {
		String allHql = this.getHql(hql, filterPropertyMap, sortValueMap);

		if (pageRequest.isCountTotal()) {
			long totalCount = findTotalCountByQuery(QueryUtil
					.converSelectSqlToCountSql(allHql));
			pageRequest.setTotalRecords(totalCount);
			pageRequest.refresh(pageRequest.getPageNo());
		}

		List result = this.findListByQueryPaging(allHql,
				pageRequest.getOffset(),
				pageRequest.getOffset() + pageRequest.getPageSize());
		Page<T> page = new Page(pageRequest);
		page.setResult(result);
		return page;
	}

	/**
	 * 按Criteria分页查询.
	 * 
	 * @param page
	 *            分页参数.
	 * @param criterions
	 *            数量可变的Criterion.
	 * 
	 * @return 分页查询结果.附带结果列表及所有查询输入参数.
	 */
	@SuppressWarnings("unchecked")
	public Page<T> findPage(final PageRequest pageRequest,
			final Criterion... criterions) {
		AssertUtils.notNull(pageRequest, "page不能为空");

		Criteria c = createCriteria(criterions);

		if (pageRequest.isCountTotal()) {
			long totalCount = countCriteriaResult(c);
			pageRequest.setTotalRecords(totalCount);
			pageRequest.refresh(pageRequest.getPageNo());
		}

		setPageRequestToCriteria(c, pageRequest);

		List result = c.list();
		Page<T> page = new Page(pageRequest);
		page.setResult(result);
		return page;
	}

	public Page<T> findPageByCriteria(final PageRequest pageRequest,
			final DetachedCriteria detachedCriteria) {
		AssertUtils.notNull(pageRequest, "page不能为空");

		Criteria c = detachedCriteria.getExecutableCriteria(getSession());

		if (pageRequest.isCountTotal()) {
			long totalCount = countCriteriaResult(c);
			pageRequest.setTotalRecords(totalCount);
			pageRequest.refresh(pageRequest.getPageNo());
		}

		setPageRequestToCriteria(c, pageRequest);

		List result = c.list();
		Page<T> page = new Page(pageRequest);
		page.setResult(result);
		return page;
	}

	public long findByCondition(final String hql,
			final Map<String, Object> filterPropertyMap,
			final Map<String, String> sortValueMap) {
		String allHql = this.getHql(hql, filterPropertyMap, sortValueMap);
		return findTotalCountByQuery(QueryUtil
				.converSelectSqlToCountSql(allHql));
	}

	public Page<T> findPageByHql(final PageRequest pageRequest, String hql,
			final Object... values) {
		AssertUtils.notNull(pageRequest, "pageRequest不能为空");
		AssertUtils.notNull(hql, "hql不能为空");

		if (pageRequest.isCountTotal()) {
			long totalCount = countHqlResult(hql, values);
			pageRequest.setTotalRecords(totalCount);
			pageRequest.refresh(pageRequest.getPageNo());
		}

		if (pageRequest.isOrderBySetted()) {
			hql = setOrderParameterToHql(hql, pageRequest);
		}
		Query q = createQuery(hql, values);

		setPageParameterToQuery(q, pageRequest);

		List result = q.list();
		Page<T> page = new Page(pageRequest);
		page.setResult(result);
		return page;
	}

	/**
	 * 按HQL分页查询.
	 * 
	 * @param page
	 *            分页参数.
	 * @param hql
	 *            hql语句.
	 * @param values
	 *            命名参数,按名称绑定.
	 * 
	 * @return 分页查询结果, 附带结果列表及所有查询输入参数.
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Page<T> findPageByHql(final PageRequest pageRequest, String hql,
			final Map<String, ?> values) {
		AssertUtils.notNull(pageRequest, "pageRequest不能为空");
		AssertUtils.notNull(hql, "hql不能为空");

		if (pageRequest.isCountTotal()) {
			long totalCount = countHqlResult(hql, values);
			pageRequest.setTotalRecords(totalCount);
			pageRequest.refresh(pageRequest.getPageNo());
		}

		if (pageRequest.isOrderBySetted()) {
			hql = setOrderParameterToHql(hql, pageRequest);
		}

		Query q = createQuery(hql, values);
		setPageParameterToQuery(q, pageRequest);

		List result = q.list();
		Page<T> page = new Page(pageRequest);
		page.setResult(result);
		return page;
	}

	public <X> Page<X> findPageBySql(final PageRequest pageRequest, String sql,
			final Map<String, Object> values) {
		AssertUtils.notNull(pageRequest, "pageRequest不能为空");
		AssertUtils.notNull(sql, "sql不能为空");

		if (pageRequest.isCountTotal()) {
			long totalCount = countSqlResult(sql, values);
			pageRequest.setTotalRecords(totalCount);
			pageRequest.refresh(pageRequest.getPageNo());
		}

		if (pageRequest.isOrderBySetted()) {
			sql = setOrderParameterToHql(sql, pageRequest);
		}
		Query q = createSQLQuery(sql, values);

		setPageParameterToQuery(q, pageRequest);

		List result = q.list();
		Page<X> page = new Page(pageRequest);
		page.setResult(result);
		return page;
	}

	public <X> List<X> findListBySql(String sql, final Object... values) {
		AssertUtils.notNull(sql, "sql不能为空");

		Query q = createSQLQuery(sql, values);

		List result = q.list();
		return result;
	}

	public <X> Page<X> findPageBySql(final PageRequest pageRequest, String sql,
			final Object... values) {
		AssertUtils.notNull(pageRequest, "pageRequest不能为空");
		AssertUtils.notNull(sql, "sql不能为空");

		if (pageRequest.isCountTotal()) {
			long totalCount = countSqlResult(sql, values);
			pageRequest.setTotalRecords(totalCount);
			pageRequest.refresh(pageRequest.getPageNo());
		}

		if (pageRequest.isOrderBySetted()) {
			sql = setOrderParameterToHql(sql, pageRequest);
		}
		Query q = createSQLQuery(sql, values);

		setPageParameterToQuery(q, pageRequest);

		List result = q.list();
		Page<X> page = new Page(pageRequest);
		page.setResult(result);
		return page;
	}

	/**
	 * 执行count查询获得本次Hql查询所能获得的对象总数.
	 * 
	 * 本函数只能自动处理简单的hql语句,复杂的hql查询请另行编写count语句查询.
	 */
	protected long countHqlResult(final String hql, final Object... values) {
		String countHql = prepareCountHql(hql);

		try {
			Long count = findUnique(countHql, values);
			return count;
		} catch (Exception e) {
			throw new RuntimeException("hql can't be auto count, hql is:"
					+ countHql, e);
		}
	}

	/**
	 * 执行count查询获得本次Hql查询所能获得的对象总数.
	 * 
	 * 本函数只能自动处理简单的hql语句,复杂的hql查询请另行编写count语句查询.
	 */
	protected long countHqlResult(final String hql,
			final Map<String, Object> values) {
		String countHql = prepareCountHql(hql);

		try {
			Long count = findUnique(countHql, values);
			return count;
		} catch (Exception e) {
			throw new RuntimeException("hql can't be auto count, hql is:"
					+ countHql, e);
		}
	}

	protected long countSqlResult(final String sql, final Object... values) {
		String countSql = prepareCountHql(sql);

		try {
			Long count = Long.valueOf(findSQLUnique(countSql, values)
					.toString());
			return count;
		} catch (Exception e) {
			throw new RuntimeException("sql can't be auto count, hql is:"
					+ countSql, e);
		}
	}

	protected long countSqlResult(final String sql,
			final Map<String, Object> values) {
		String countHql = prepareCountHql(sql);

		try {
			Long count = Long.valueOf(findSQLUnique(countHql, values)
					.toString());
			return count;
		} catch (Exception e) {
			throw new RuntimeException("hql can't be auto count, hql is:"
					+ countHql, e);
		}
	}

	/**
	 * 在HQL的后面添加分页参数定义的orderBy, 辅助函数.
	 */
	protected String setOrderParameterToHql(final String hql,
			final PageRequest pageRequest) {
		StringBuilder builder = new StringBuilder(hql);
		builder.append(" order by");

		for (Sort orderBy : pageRequest.getSort()) {
			builder.append(String.format(" %s %s,", orderBy.getProperty(),
					orderBy.getDir()));
		}

		if (builder.charAt(builder.length() - 1) == ',') {
			builder.deleteCharAt(builder.length() - 1);
		} else {
			builder.setLength(0);
		}

		return builder.toString();
	}

	/**
	 * 设置分页参数到Query对象,辅助函数.
	 */
	protected Query setPageParameterToQuery(final Query q,
			final PageRequest pageRequest) {
		q.setFirstResult(pageRequest.getOffset());
		q.setMaxResults(pageRequest.getPageSize());
		return q;
	}

	/**
	 * 设置分页参数到Criteria对象,辅助函数.
	 */
	protected Criteria setPageRequestToCriteria(final Criteria c,
			final PageRequest pageRequest) {
		AssertUtils.isTrue(pageRequest.getPageSize() > 0,
				"Page Size must larger than zero");

		c.setFirstResult(pageRequest.getOffset());
		c.setMaxResults(pageRequest.getPageSize());

		if (pageRequest.isOrderBySetted()) {
			for (Sort sort : pageRequest.getSort()) {
				if (Sort.ASC.equals(sort.getDir())) {
					c.addOrder(Order.asc(sort.getProperty()));
				} else {
					c.addOrder(Order.desc(sort.getProperty()));
				}
			}
		}
		return c;
	}

	private String prepareCountHql(String orgHql) {
		String countHql = "select count(*) "
				+ removeSelect(removeOrders(orgHql));
		return countHql;
	}

	private static String removeSelect(String hql) {
		int beginPos = hql.toLowerCase().indexOf("from");
		return hql.substring(beginPos);
	}

	private static String removeOrders(String hql) {
		Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*",
				Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(hql);
		StringBuffer sb = new StringBuffer();
		while (m.find()) {
			m.appendReplacement(sb, "");
		}
		m.appendTail(sb);
		return sb.toString();
	}

	// -- 属性过滤条件(PropertyFilter)查询函数 --//

	/**
	 * 按属性查找对象列表,支持多种匹配方式.
	 * 
	 * @param matchType
	 *            匹配方式,目前支持的取值见PropertyFilter的MatcheType enum.
	 */
	public List<T> findBy(final String propertyName, final Object value,
			final MatchType matchType) {
		Criterion criterion = buildCriterion(propertyName, value, matchType);
		return findListByCriteria(criterion);
	}

	/**
	 * 按属性过滤条件列表查找对象列表.
	 */
	public List<T> find(List<PropertyFilter> filters) {
		Criterion[] criterions = buildCriterionByPropertyFilter(filters);
		return findListByCriteria(criterions);
	}

	/**
	 * 执行count查询获得本次Criteria查询所能获得的对象总数.
	 */
	@SuppressWarnings("unchecked")
	protected long countCriteriaResult(final Criteria c) {
		CriteriaImpl impl = (CriteriaImpl) c;

		// 先把Projection、ResultTransformer、OrderBy取出来,清空三者后再执行Count操作
		Projection projection = impl.getProjection();
		ResultTransformer transformer = impl.getResultTransformer();

		List<CriteriaImpl.OrderEntry> orderEntries = null;
		try {
			orderEntries = (List) ReflectionUtils.getFieldValue(impl,
					"orderEntries");
			ReflectionUtils
					.setFieldValue(impl, "orderEntries", new ArrayList());
		} catch (Exception e) {
			logger.error("不可能抛出的异常:{}", e.getMessage());
		}

		// 执行Count查询
		Long totalCountObject = (Long) c.setProjection(Projections.rowCount())
				.uniqueResult();
		long totalCount = (totalCountObject != null) ? totalCountObject : 0;

		// 将之前的Projection,ResultTransformer和OrderBy条件重新设回去
		c.setProjection(projection);

		if (projection == null) {
			c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
		}
		if (transformer != null) {
			c.setResultTransformer(transformer);
		}
		try {
			ReflectionUtils.setFieldValue(impl, "orderEntries", orderEntries);
		} catch (Exception e) {
			logger.error("不可能抛出的异常:{}", e.getMessage());
		}

		return totalCount;
	}

	/**
	 * 按属性条件参数创建Criterion,辅助函数.
	 */
	protected Criterion buildCriterion(final String propertyName,
			final Object propertyValue, final MatchType matchType) {
		AssertUtils.hasText(propertyName, "propertyName不能为空");
		Criterion criterion = null;
		// 根据MatchType构造criterion
		switch (matchType) {
		case EQ:
			criterion = Restrictions.eq(propertyName, propertyValue);
			break;
		case LIKE:
			criterion = Restrictions.like(propertyName, (String) propertyValue,
					MatchMode.ANYWHERE);
			break;

		case LE:
			criterion = Restrictions.le(propertyName, propertyValue);
			break;
		case LT:
			criterion = Restrictions.lt(propertyName, propertyValue);
			break;
		case GE:
			criterion = Restrictions.ge(propertyName, propertyValue);
			break;
		case GT:
			criterion = Restrictions.gt(propertyName, propertyValue);
			break;
		case NE:
			criterion = Restrictions.ne(propertyName, propertyValue);
			break;
		}
		return criterion;
	}

	/**
	 * 按属性条件列表创建Criterion数组,辅助函数.
	 */
	protected Criterion[] buildCriterionByPropertyFilter(
			final List<PropertyFilter> filters) {
		List<Criterion> criterionList = new ArrayList<Criterion>();
		for (PropertyFilter filter : filters) {
			if (!filter.hasMultiProperties()) { // 只有一个属性需要比较的情况.
				Criterion criterion = buildCriterion(filter.getPropertyName(),
						filter.getMatchValue(), filter.getMatchType());
				criterionList.add(criterion);
			} else {// 包含多个属性需要比较的情况,进行or处理.
				Disjunction disjunction = Restrictions.disjunction();
				for (String param : filter.getPropertyNames()) {
					Criterion criterion = buildCriterion(param,
							filter.getMatchValue(), filter.getMatchType());
					disjunction.add(criterion);
				}
				criterionList.add(disjunction);
			}
		}
		return criterionList.toArray(new Criterion[criterionList.size()]);
	}
}
